<template>
  <!-- 设备信息表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="800px"
    draggable
    @close="closeDialog"
    destroy-on-close
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="110">
      <el-row>
        <el-col :span="12">
          <el-form-item label="参数名" prop="parameterName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.parameterName"
              placeholder="请输入参数名"
              clearable
            />
            <span v-else>{{ formData.parameterName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="地址" prop="url">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.url"
              placeholder="请输入地址"
              clearable
            />
            <span v-else>{{ formData.url }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="参数描述" prop="parameterDesc">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.parameterDesc"
              placeholder="请输入参数描述"
              clearable
            />
            <span v-else>{{ formData.parameterDesc }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数据类型" prop="parameterType">
            <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.parameterType"
              placeholder="请选择数据类型"
              clearable
              @change="parameterTypeChange"
            >
              <el-option
                v-for="item in useDictionary('ScaDataType')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span v-else>{{ formData.parameterType }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="collectionFrequency" label="采集方式">
            <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.collectionFrequency"
              placeholder="请选择采集方式"
            >
              <el-option
                v-for="item in useDictionary('ScaCollectFrequency')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span v-else>{{ formData.collectionFrequency }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.collectionFrequency == 2">
          <el-form-item prop="collectionFrequencyTime" label="采集频率">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.collectionFrequencyTime"
              placeholder=""
              class="input-with-select"
            >
              <template #append>
                <el-select
                  v-model="formData.collectionFrequencyUnit"
                  placeholder=""
                  style="width: 70px"
                >
                  <el-option label="秒" value="s" />
                  <el-option label="分钟" value="m" />
                </el-select>
              </template>
            </el-input>
            <span v-else
              >{{ formData.collectionFrequencyTime
              }}{{
                formData.collectionFrequencyUnit === "s"
                  ? "秒"
                  : formData.collectionFrequencyUnit === "m"
                  ? "分钟"
                  : ""
              }}</span
            >
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="paramType" label="参数类别">
            <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.paramType"
              placeholder="请选择参数类别"
              clearable
            >
              <el-option
                v-for="item in useDictionary('ScaParamType')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span v-else>{{ formData.paramType }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="计量单位" prop="measurementUnit">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.measurementUnit"
              placeholder="请输入计量单位"
              clearable
            />
            <span v-else>{{ formData.measurementUnit }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示方式" prop="showType">
            <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.showType"
              placeholder="请选择显示方式"
              clearable
            >
              <el-option
                v-for="item in useDictionary('ScaShowType')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span v-else>{{ formData.showType }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="序号" prop="sort">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.sort"
              placeholder="请输入序号"
              clearable
            />
            <span v-else>{{ formData.sort }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              placeholder="请输入备注"
              clearable
            />
            <span v-else>{{ formData.remarks }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <div style="font-weight: 700">有效规则</div>
      <el-divider style="margin: 10px 0" />
      <el-row>
        <el-col :span="6">
          <el-form-item prop="validationRuleType" label-width="0">
            <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.validationRuleType"
              placeholder="请选择有效规则"
              clearable
              @change="validationRuleTypeChange"
            >
              <el-option
                v-for="item in useDictionary('ScaDataRule')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span v-else>{{ formData.validationRuleType }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="formData.validationRuleType === '1'">
        <el-col :span="12">
          <el-form-item label="最小值" prop="lowerLimitValue">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.lowerLimitValue"
              placeholder="请输入最小值"
              clearable
            />
            <span v-else>{{ formData.lowerLimitValue }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大值" prop="upperLimitValue">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.upperLimitValue"
              placeholder="请输入最大值"
              clearable
            />
            <span v-else>{{ formData.upperLimitValue }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="formData.validationRuleType === '2'">
        <el-col :span="24">
          <el-form-item label="枚举值" prop="enumValueList">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.enumValueList"
              placeholder="请输入枚举值 以逗号隔开 例如1,2,3"
              clearable
            />
            <span v-else>{{ formData.enumValueList }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { validateNumber } from "@/utils/commonHooks";
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import { useRoute } from "vue-router";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "SCAEQUIPTYPECOLLETEDIR",
  inheritAttrs: false,
});
const route = useRoute();
const emit = defineEmits(["reset-table", "change-visible"]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);
const rules = reactive({
  parameterName: [{ required: true, message: "请输入参数名", trigger: "blur" }],
  paramType: [{ required: true, message: "请选择参数类别", trigger: "change" }],
  collectionFrequency: [
    { required: true, message: "请选择采集方式", trigger: "change" },
  ],
  url: [
    { required: true, message: "请输入地址", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  parameterDesc: [
    { required: true, message: "请输入参数描述", trigger: "blur" },
  ],
  collectionFrequencyTime: [
    { required: true, message: "请输入采集频率", trigger: "blur" },
    { required: true, validator: validateNumber, trigger: "blur" },
  ],
  parameterType: [
    { required: true, message: "请选择数据类型", trigger: "change" },
  ],
  showType: [{ required: true, message: "请选择显示方式", trigger: "change" }],
  sort: [
    {
      required: true,
      message: "请输入序号",
      trigger: "blur",
      validator: validator,
    },
  ],
  lowerLimitValue: [
    {
      required: true,

      trigger: "blur",
      validator: validator,
    },
  ],
  upperLimitValue: [
    {
      required: true,

      trigger: "blur",
      validator: validator,
    },
  ],
  enumValueList: [
    {
      required: true,
      pattern: /^(?!\s*$)(?!.*[\uFF0C])(?:[^,\s]+(?:,\s*[^,\s]+)*)?$/u,
      message: "请输入枚举值 以英文逗号隔开 例如1,2,3",
      trigger: "blur",
      // validator: validator1,
    },
  ],
});

function validator(rule, value, callback: (a?: any) => {}) {
  if (!value && value != "0") {
    //先判断空可以过
    callback(new Error("请输入数值型数据，精度支持保留四位小数"));
  } else {
    if (/^\d{1,6}(\.\d{0,4})?$/.test(value)) {
      //验证正整数和0的正则
      return true;
    } else {
      callback(new Error("请输入数值型数据，精度支持保留四位小数"));
    }
  }
}

const formRef = ref(ElForm);

let formData: any = reactive({
  deleted: 0,
  enabled: 0,
  enumValueList: "",
  enumerationValue: "",
  id: "",
  ids: [],
  lowerLimitValue: "",
  maxValue: "",
  measurementUnit: "",
  collectionFrequency: "2",
  collectionFrequencyTime: "",
  collectionFrequencyUnit: "m",
  paramType: "",
  minValue: "",
  parameterDesc: "",
  parameterName: "",
  parameterType: "",
  relationId: "",
  relationType: "",
  remarks: "",
  roleType: "",
  showType: "",
  sort: "",
  upperLimitValue: "",
  url: "",
  validationRuleType: "",
  version: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        deleted,
        enabled,
        enumValueList,
        enumerationValue,
        id,
        ids,
        lowerLimitValue,
        maxValue,
        measurementUnit,
        collectionFrequency,
        collectionFrequencyTime,
        collectionFrequencyUnit,
        paramType,
        minValue,
        parameterDesc,
        parameterName,
        parameterType,
        relationId,
        relationType,
        remarks,
        roleType,
        showType,
        sort,
        upperLimitValue,
        url,
        validationRuleType,
        version,
      } = newVal;
      Object.assign(formData, {
        deleted,
        enabled,
        enumValueList,
        enumerationValue,
        id,
        ids,
        lowerLimitValue,
        maxValue,
        measurementUnit,
        collectionFrequency,
        collectionFrequencyTime,
        collectionFrequencyUnit,
        paramType,
        minValue,
        parameterDesc,
        parameterName,
        parameterType,
        relationId,
        relationType,
        remarks,
        roleType,
        showType,
        sort,
        upperLimitValue,
        url,
        validationRuleType,
        version,
      });

      formData.parameterType && parameterTypeChange(formData.parameterType);
      formData.showType = newVal.showType;
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.deleted = 0;
  formData.enabled = 0;
  formData.enumValueList = "";
  formData.enumerationValue = "";
  formData.id = "";
  formData.ids = [];
  formData.lowerLimitValue = "";
  formData.maxValue = "";
  formData.measurementUnit = "";
  formData.collectionFrequency = "2";
  formData.collectionFrequencyTime = "";
  formData.collectionFrequencyUnit = "m";
  formData.paramType = "";
  formData.minValue = "";
  formData.parameterDesc = "";
  formData.parameterName = "";
  formData.parameterType = "";
  formData.relationId = "";
  formData.relationType = "";
  formData.remarks = "";
  formData.roleType = "";
  formData.showType = "";
  formData.sort = "";
  formData.upperLimitValue = "";
  formData.url = "";
  formData.validationRuleType = "";
  formData.version = "";
}
const loading = ref(false);

/** 设备信息保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      if (
        formData.lowerLimitValue &&
        formData.upperLimitValue &&
        Number(formData.lowerLimitValue) > Number(formData.upperLimitValue)
      ) {
        ElMessage.error("最大值不能小于最小值");
        return;
      }
      formData.relationId = route.query.id;
      console.log(formData);
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/iotadmin/scaequiptype/saveCollectionParam",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      console.log(formData.id);

      emit("reset-table", formData.id);
    }
  });
}

const validationRuleTypeChange = (e) => {
  formData.lowerLimitValue = "";
  formData.upperLimitValue = "";
  formData.enumValueList = "";
};

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

// 数据类型为浮点和整型，可选择显示方式为仪表盘和标签；否则只能选择显示方式为标签
const scaShowTypeList: any = ref([]);
const scaShowType = useDictionary("ScaShowType");

function parameterTypeChange(e: any) {
  formData.showType = "";
  if (e === "integer" || e === "float") {
    scaShowTypeList.value = scaShowType;
  } else {
    const index = scaShowType.findIndex((self: any) => self.label === "标签");
    scaShowTypeList.value = [scaShowType[index]];
  }
}
</script>
<style lang="scss" scoped></style>
